/**
 * Filename: ThemeListAdapter.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/4/14 11:57
 */
package com.github.postsanf.yinian.adapter;

import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNTheme;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.Logger;
import com.github.postsanf.yinian.utils.SkinConfig;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;

import java.io.File;
import java.util.List;

public class ThemeListAdapter extends RecyclerView.Adapter<ThemeListAdapter.ViewHolder>{
    private Context context;
    private List<YNTheme> datas;
    public static Resources mResource;
    private DownloadManager manager;

    public ThemeListAdapter(Context context, List<YNTheme> datas,DownloadManager manager) {
        this.context = context;
        this.datas = datas;
        this.manager = manager;
    }

    public void setResource(Resources mResource){
        this.mResource  = mResource;
    }

    public  class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout ll_item_theme;
        SimpleDraweeView    iv_item_theme_bg;
        Button         btn_theme_switch;

        public ViewHolder(View itemView) {
            super(itemView);
            ll_item_theme	= (LinearLayout) itemView
                    .findViewById(R.id.ll_item_theme);
            iv_item_theme_bg = (SimpleDraweeView) itemView
                    .findViewById(R.id.iv_item_theme_bg);
            btn_theme_switch=(Button) itemView
                    .findViewById(R.id.btn_theme_switch);
        }

        public void bindData(final YNTheme listItems,int position)
        {
            if (listItems != null)
            {
                if(position == 0){
                    ImageLoader.getInstance().displayImage("http://www.zhuiyinanian.com/yinian/theme/Android/theme_defualt.png", new ImageViewAware(iv_item_theme_bg, false),ImageOptHelper.getImgOptions());
                    if (new File(SkinConfig.getInstance(context.getApplicationContext()).getSkinResourcePath()).isDirectory() || !new File(SkinConfig.getInstance(context.getApplicationContext()).getSkinResourcePath()).exists() || SkinConfig.getInstance(context.getApplicationContext()).getSkinResourcePath().equals("")){
                        btn_theme_switch.setText("当前主题");
                    }else{
                        btn_theme_switch.setText("应用主题");
                    }
                    btn_theme_switch.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SkinConfig.getInstance(context.getApplicationContext()).setSkinResourcePath(""); // 保存资源路径
                            SkinPackageManager.getInstance(context.getApplicationContext()).mResources = null;
                            context.sendBroadcast(new Intent(ACTIONs.SKIN_ACTION));
                            ThemeListAdapter.this.notifyDataSetChanged();
                        }
                    });
                }else{
                    Uri uri = Uri.parse(listItems.getTpic());
                    ImageOptHelper.showFrescoHome(uri, iv_item_theme_bg, context);
                    final String downUrl = listItems.getTurl();
                    final String themename = downUrl.substring(downUrl.lastIndexOf("/")+1);
                    File skin=new File(Environment.getExternalStorageDirectory(),"yinian/plugins/"+themename);
                    if (SkinConfig.getInstance(context.getApplicationContext()).getSkinResourcePath().equals(skin.getPath())) {
                        btn_theme_switch.setText("当前主题");
                    }else if(skin.exists()){
                        btn_theme_switch.setText("应用主题");
                    }else{
                        btn_theme_switch.setText("下载主题");
                    }
                    // 点击列表
                    btn_theme_switch.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            File dir=new File(Environment.getExternalStorageDirectory(),"yinian/plugins");
                            File skin=new File(dir,themename);
                            if(skin.exists())
                            {
                                SkinPackageManager.getInstance(context.getApplicationContext()).loadSkinAsync(skin.getAbsolutePath(), new SkinPackageManager.loadSkinCallBack() {
                                    @Override
                                    public void startloadSkin(){
                                    }
                                    @Override
                                    public void loadSkinSuccess(){
                                        context.sendBroadcast(new Intent(ACTIONs.SKIN_ACTION));
                                        ThemeListAdapter.this.notifyDataSetChanged();
                                        btn_theme_switch.setText("当前主题");
                                    }
                                    @Override
                                    public void loadSkinFail() {
                                    }
                                });
                            }else{
                                downTheme(downUrl,themename);
                            }
                        }
                    });
                }
            }
        }
    }

    private YNTheme getItem(int position) {
        return datas.get(position);
    }

    // 创建ViewHolder
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.yn_item_theme, parent, false);
        return new ViewHolder(convertView);
    }

    // 绑定数据到View
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position){
        YNTheme listItems = position==0 ? new YNTheme():getItem(position - 1);
        holder.bindData(listItems,position);

        if(mResource!=null) {
            holder.btn_theme_switch.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel",  CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            holder.btn_theme_switch.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
        }
        holder.itemView.setTag(listItems);
    }

    @Override
    public int getItemCount() {
        return  datas.size()+1;
    }

    private void  downTheme(String url,String name){
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/plugins");
        if(!(file.mkdir() || file.isDirectory())){
            file.mkdirs();
        }
        //创建下载请求
        DownloadManager.Request down=new DownloadManager.Request (Uri.parse(url));
        //设置允许使用的网络类型，这里是移动网络和wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //禁止发出通知，既后台下载
        down.setShowRunningNotification(false);
        //不显示下载界面
        down.setVisibleInDownloadsUi(false);
        //设置下载后文件存放的位置
        down.setDestinationInExternalPublicDir("yinian/plugins/", name);
        //将下载请求放入队列
        manager.enqueue(down);
    }
}
